<?php

namespace app\common\service;

use app\common\exception\BusinessException;
use app\common\model\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

/**
 * 统一登录服务
 */
class SsoService
{
    private string $appId;

    private string $appApi;

    /**
     * @throws DataNotFoundException
     * @throws BusinessException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function __construct($appId)
    {
        $appModel = new App();
        $appInfo = $appModel->getAppById($appId);
        if (empty($appInfo['app_host'])) {
            throw new BusinessException('租户app_host不能为空');
        }
        $this->appId = $appId;
        $this->appApi = buildUrl($appInfo['app_host']);
    }

    public function getAppId(): string
    {
        return $this->appId;
    }

    public function setAppId(string $appId): SsoService
    {
        $this->appId = $appId;
        return $this;
    }

    /**
     * execute
     * @param string $path
     * @return mixed
     * @throws BusinessException
     */
    public function execute(string $path, $data)
    {
        $api = $this->appApi . $path;
        $header = [
            'appId:' . $this->appId,
        ];
        $responseData = \curl($api, $data, true, $header);
        if (!$responseData) {
            throw new BusinessException('请求远程接口失败');
        }
        if ($responseData['code'] != 1) {
            throw new BusinessException($responseData['message']);
        }
        return $responseData['data'];
    }


}